//
//  AppDelegate.m
//  BaiduMapSdkSrc
//
//  Created by baidu on 13-3-21.
//  Copyright (c) 2013年 baidu. All rights reserved.
//

#import "AppDelegate.h"
#import "DSLogger.h"
#import "AFNetworkReachabilityManager.h"
#import "BaseNavigationController.h"
#import "MySpeakerManager.h"
#import "AppUtils.h"
#import "LoginDataMng.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import "UIViewController+Alert.h"
#import "MainViewController.h"
#import "DDMenuController.h"
#import "UserInfoViewController.h"
#import "GuideViewController.h"
#import "Config.h"
//#import "BNCoreServices.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能所有的头文件


@interface AppDelegate ()<UIAlertViewDelegate, UNUserNotificationCenterDelegate>
{
    BOOL isLaunch;
    BOOL hasCheckAccount;
    
    NSDictionary *notificationUserInfo;//通过通知启动的通知消息保存，等应用加载完后进行处理
    //    BOOL _ProcessFlag; //铃声执行的情况，同一时间只有一个铃声
        BMKMapManager* _mapManager;
    
}
@end

@implementation AppDelegate
@synthesize serverMng;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    NSLog(@"---%@-----version=%f",NSHomeDirectory(), [UIDevice currentDevice].systemVersion.floatValue );
    isLaunch = YES;
    
    // 要使用百度地图，请先启动BaiduMapManager
    _mapManager = [[BMKMapManager alloc]init];
    
    /**
     *百度地图SDK所有接口均支持百度坐标（BD09）和国测局坐标（GCJ02），用此方法设置您使用的坐标类型.
     *默认是BD09（BMK_COORDTYPE_BD09LL）坐标.
     *如果需要使用GCJ02坐标，需要设置CoordinateType为：BMK_COORDTYPE_COMMON.
     */
    if ([BMKMapManager setCoordinateTypeUsedInBaiduMapSDK:BMK_COORDTYPE_BD09LL]) {
        NSLog(@"经纬度类型设置成功");
    } else {
        NSLog(@"经纬度类型设置失败");
    }
    
    // 如果要关注网络及授权验证事件，请设定     generalDelegate参数
    BOOL ret = [_mapManager start:BM_KEY  generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
//    //初始化导航SDK
//    [BNCoreServices_Instance initServices: BM_KEY];
//    [BNCoreServices_Instance startServicesAsyn:nil fail:nil];
    
    [DSLogger StartLogCrashInfo];
    
    //      [self initUmShareInfo];
    //
    //      [[MySpeakerManager sharedInstance] initSpeaker];
    //
    //        [self registerPush:application launchOptions:launchOptions];
    
//        初始化界面  -- 放在通知初始化后面
    [self initMyCommonUI];

    return YES;
}


//ios<9.0 urlScheme打开
//- (BOOL)application:(UIApplication *)application openURL: (NSURL*)url sourceApplication:(NSString *) sourceApplication annotation:(id)annotation
//{
//    BOOL result = [UMSocialSnsService handleOpenURL:url];
//    return result;
//}

#pragma marker 注册deviceToken
// 当 DeviceToken 获取失败时，系统会回调此方法
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"BPush: DeviceToken 获取失败，原因：%@",error);
}

/// iOS8下申请DeviceToken
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerForRemoteNotifications)]) {
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
}
#endif

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    //下面是云推送的代码
    NSString *token  =[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""] stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""];
    NSString *log = [NSString stringWithFormat:@"deviceToken=%@",token];
    NSLog(@"%@",log);
    if([ServerMng sharedServerMng].showSavearray){
        [[ServerMng sharedServerMng].saveArray addObject:log];
    }
//    [CloudPushSDK registerDevice:deviceToken];
    // 打印到日志
    NSLog(@"%@", [NSString stringWithFormat:@"云旺: Register use deviceToken : %@", deviceToken]);
}

// 通知统计回调 （开着app情况下-ios9）
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    // App 收到推送的通知
    
    NSLog(@"%@", [NSString stringWithFormat:@"BPush: Received Remote Notification :\n%@", userInfo]);
    UIApplicationState state = application.applicationState;
    
//    // 语音播报
//    if (nil != userInfo[@"aps"] && (state == UIApplicationStateActive || state == UIApplicationStateBackground)) {
//        if (LOGIN_USER.isVoiceOpen) {
//            NSString *apsString = [AppUtils toString:userInfo[@"audio_text"]]  ;
//            [[MySpeakerManager sharedInstance] speakString:apsString immediately:YES];
//        }
//    }
    
    // 应用在前台 或者后台开启状态下，不跳转页面，让用户选择。
//    NSString *storeNoti = userInfo[@"store_order_status_notify"];
//    NSString *orderNoti = userInfo[@"off_line_order_complete_notify"];
//    NSString *payno = userInfo[@"pay_interface_no"];
//    if (![AppUtils isEmpty:orderNoti] && ![AppUtils isEmpty:payno]) {
//        // 是否登录状态
//        if ([AppUtils isLogout]) {
//            [[LoginDataMng sharedInstance] setJumpPayNo:payno];
//        }
//        else {
//            [[LoginDataMng sharedInstance] setJumpPayNo:payno];
//            if (state == UIApplicationStateActive || state == UIApplicationStateBackground) {
//                [self showIncomeAlert];
//            }
//            else
//            {
//                // 杀死状态下，直接跳转到跳转页面。
//                IncomeType type = [[StoreManager sharedInstance] incomeTypeByChannelNo:payno];
//                //                [[LoginDataMng sharedInstance] jumpIncomeViewController:type];
//            }
//        }
//    }
//    
//    if (![AppUtils isEmpty:storeNoti]) {
//        [self updateCurrentView];
//    }
}

- (void)updateCurrentView
{
    UIViewController *controller = [AppUtils currentViewController];
    if (nil != controller && [controller isKindOfClass:[BaseViewController class]]) {
        BaseViewController *baseController = (BaseViewController *)controller;
        [baseController requestData];
    }
}

- (void)showIncomeAlert
{
    //    UIViewController *controller2 = [[AppUtils getNavigationController].viewControllers lastObject];
    //
    //    if([controller2 respondsToSelector:@selector(showAlertWithTitle:message:cancelBottonTitle:otherButtonTitle:clickBlock:)]){
    //        [controller2 showAlertWithTitle:@"温馨提示" message:@"您有新的收款通知，是否立即查看?" cancelBottonTitle:@"取消" otherButtonTitle:@"确定" clickBlock:^(NSInteger btnIndex) {
    //            if(btnIndex == 1){
    //                [ServerMng sharedServerMng].alertShowFlag = NO;
    //                NSString *payno = [[LoginDataMng sharedInstance] jumpPayNo];
    //                IncomeType type = [[StoreManager sharedInstance] incomeTypeByChannelNo:payno];
    //                if (type < IncomeType_Count) {
    //                    [[LoginDataMng sharedInstance] jumpIncomeViewController:type];
    //                    [[LoginDataMng sharedInstance] setJumpPayNo:@""];
    //                }
    //            }
    //        }];
    //    }
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您有新的收款通知，是否立即查看?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert setTag:1];
    [alert show];
}

// iOS 10   App 应用在线的情况下收到远程/本地推送会被调用
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    if(serverMng.showSavearray){
        [serverMng.saveArray addObject:[AppUtils toJSONString:userInfo]];
    }
//    // 语音播报
//    if (nil != userInfo[@"aps"] ) {
//        if (LOGIN_USER.isVoiceOpen) {
//            NSString *apsString = [AppUtils toString:userInfo[@"audio_text"]];
//            [[MySpeakerManager sharedInstance] speakString:apsString immediately:YES];
//        }
//    }
    
    // 应用在前台 或者后台开启状态下，不跳转页面，让用户选择。
    NSString *storeNoti = userInfo[@"store_order_status_notify"];
    NSString *orderNoti = userInfo[@"off_line_order_complete_notify"];
    NSString *payno = userInfo[@"pay_interface_no"];
    if (![AppUtils isEmpty:orderNoti] && ![AppUtils isEmpty:payno]) {
        // 是否登录状态
        if ([AppUtils isLogout]) {
            [[LoginDataMng sharedInstance] setJumpPayNo:payno];
        }
        else {
            [[LoginDataMng sharedInstance] setJumpPayNo:payno];
            [self showIncomeAlert];
            if(serverMng.showSavearray){
                [serverMng.saveArray addObject:@"用户回来吗"];
            }
        }
    }
    
    if (![AppUtils isEmpty:storeNoti]) {
        [self updateCurrentView];
    }
}

// iOS 10   点击远程/本地通知启动 App 时被调用
//- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{}

#pragma mark 注册苹果的推送

- (void)registerPush:application launchOptions:(NSDictionary *)launchOptions
{
    [self registerAPNS:application :launchOptions];
    [self init_tae];
    [self registerMsgReceive];
    
    //角标清0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void)init_tae{
//    [CloudPushSDK setEnvironment:CCPSDKEnvironmentSandBox];
//    //sdk初始化
//    [[ALBBSDK sharedInstance] setDebugLogOpen:NO];// 测试时打开
//    [[ALBBSDK sharedInstance] asyncInit:^{
//        NSLog(@"======================> 初始化成功");
//        if([ServerMng sharedServerMng].showSavearray){
//            [[ServerMng sharedServerMng].saveArray addObject:[NSString stringWithFormat:@"deviceID=%@",[CloudPushSDK getDeviceId]]];
//        }
//        //            [AppUtils postNotificationName: XGYWCloudPushInitSuccessNotification];
//        NSLog(@"======================> DeviceID：%@", [CloudPushSDK getDeviceId]);
//    }failure:^(NSError *error) {
//        NSLog(@"======================> 初始化失败:%@",error);
//    }];
}


-(void) registerAPNS :(UIApplication *)application :(NSDictionary *)launchOptions
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
        // iOS 10 Notifications
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!error && granted) {
                [application registerForRemoteNotifications];
                //                [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
                //                    NSLog(@"%@", settings);
                //                }];
            }
            else {
                NSLog(@"用户拒绝接受通知");
            }
        }];
    }
    else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        // iOS 8 Notifications
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
        [application registerForRemoteNotifications];
    }
    else {
        // iOS < 8 Notifications
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
    }
    
//    [CloudPushSDK handleLaunching:launchOptions]; // 作为 apns 消息统计
}

// 注册接收CloudChannel 推送下来的消息
- (void) registerMsgReceive {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMessageReceived:) name:@"CCPDidReceiveMessageNotification" object:nil]; // 注册
}

// 推送下来的消息抵达的处理示例（上线前如果不使用消息，则不要此外代码））
- (void)onMessageReceived:(NSNotification *)notification {
    NSData *data = [notification object];
    NSString *message = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    //     报警提示
    if(![NSThread isMainThread])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"消息" message:message delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil];
            [alertView show];
        });
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"消息" message:message delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil];
        [alertView show];
    }
}



#pragma mark 初始界面
//初始化界面，自动登录或者进入登录页面
- (void)initMyCommonUI
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    serverMng = [ServerMng sharedServerMng];
    
    serverMng.networkEnabled = YES;
    LoginDataItem *loginUser = [[LoginDataMng sharedInstance] getLoginUser];
    serverMng.loginUser = loginUser;
//        serverMng.loginUser = nil;
    [self checkNetworkInfo];
    
    BOOL showGuideView = [[Config getMyHabitUpdateVersion:NEED_NEW_GUIDE? [AppUtils currentVersion]  :nil configType:ConfigGuideViewFollowTime] isEqualToString:@"0"];
    if (showGuideView) {
        [self initGuideWindow];
    } else {
        [self initMainWindow];
    }
    //    [self initLoginWindow];
}

-(void)initGuideWindow
{
    GuideViewController *guide = [[GuideViewController alloc] init];
    self.window.rootViewController  = guide;
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
}

//初始化登陆页面
- (void)initLoginWindow
{
    LoginViewController *controller = self.loginViewController;
    if (!controller) {
        controller = [[LoginViewController alloc] init];
        self.loginViewController = controller;
    }
    [self initWindow:controller];
}

//初始首页主页面
- (void)initMainWindow
{
    MainViewController *controller = self.mainViewController;
    if (controller) {
        controller.selectedIndex = 0;
    } else {
        controller = [[MainViewController alloc] init];
        self.mainViewController = controller;
    }
    [self initWindow:controller];
}


- (void)initWindow:(UIViewController *)controller
{
    _rootNav = [[BaseNavigationController alloc] initWithRootViewController:controller];
    
    _ddMenu = [[DDMenuController alloc] initWithRootViewController:_rootNav];
    _leftViewController = [[UserInfoViewController alloc] init];
    _ddMenu.leftViewController = _leftViewController;
    self.window.rootViewController  = _ddMenu;
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
}

- (void)checkNetworkInfo
{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi) {
            serverMng.networkEnabled = YES;
            if (status == AFNetworkReachabilityStatusReachableViaWiFi) {
                serverMng.netType = NetTypeWiFi;
            } else {
                serverMng.netType = NetTypeWWAN;
            }
        } else {
            serverMng.networkEnabled = NO;
            serverMng.netType = NetTypeNone;
        }
        DSLog(@"self.networkEnabled = %d", serverMng.networkEnabled);
        if (!hasCheckAccount) {
            [self checkAccountInfo];
        }
        [AppUtils postNotificationName:XGNetworkChangedNotification];
    }];
}

/**
 * 检查账户信息
 */
- (void)checkAccountInfo
{
    if ([AppUtils isLogout]) {
        return;
    }
    
    [[LoginDataMng sharedInstance] reLogin:^(BOOL success) {
        hasCheckAccount = YES;
    }];
}


#pragma mark UIApplicationDelegate
- (void)applicationWillResignActive:(UIApplication *)application {
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [self updateCurrentView];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    
}

- (void)applicationWillTerminate:(UIApplication *)application {
    
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [ServerMng sharedServerMng].alertShowFlag = NO;
    if (buttonIndex == alertView.cancelButtonIndex) {
        return;
    }
    
    NSInteger tag = alertView.tag;
    if(tag == Tag_alert_request_msg){
        //alertView.cancelButtonIndex
    }
    else if(tag == Tag_alert_login_msg){
        BOOL needRequest = alertView.accessibilityValue.boolValue;
        if(needRequest){
            [[LoginDataMng  sharedInstance] loginOut];
        }else{
            [[LoginDataMng  sharedInstance] loginOutWithoutRequest];
        }
    }
    else if(tag == 1) {
//        NSString *payno = [[LoginDataMng sharedInstance] jumpPayNo];
//        IncomeType type = [[StoreManager sharedInstance] incomeTypeByChannelNo:payno];
//        if (type < IncomeType_Count) {
//            //            [[LoginDataMng sharedInstance] jumpIncomeViewController:type];
//            [[LoginDataMng sharedInstance] setJumpPayNo:@""];
//        }
    }
}

//注册友盟及其管理的第三方
-(void)initUmShareInfo
{
//    //UM Analytics友盟统计
//    UMConfigInstance.appKey = APP_ID_UM;
//    UMConfigInstance.channelId = @"App Store";
//    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
//    [MobClick setAppVersion:version];
//    [MobClick startWithConfigure:UMConfigInstance];
//    
//    
//    [UMSocialData setAppKey:APP_ID_UM];
//    [UMSocialData openLog:NO];
//    [UMSocialConfig setFinishToastIsHidden:YES position:UMSocialiToastPositionCenter];
//    [UMSocialWechatHandler setWXAppId:APP_ID_WX appSecret:SECRET_KEY_WX url:@"http://www.umeng.com/social"];
//    //    [UMSocialSinaSSOHandler openNewSinaSSOWithAppKey:APP_ID_WB RedirectURL:CALL_BACK_WB];
//    [UMSocialQQHandler setQQWithAppId:APP_ID_QQ appKey:@"SECRET_KEY_QQ" url:@"http://www.umeng.com/social"];
}


//地图初始化回调
- (void)onGetNetworkState:(int)iError
{
    if (0 == iError) {
        NSLog(@"联网成功");
    }
    else{
        NSLog(@"onGetNetworkState %d",iError);
    }
    
}

- (void)onGetPermissionState:(int)iError
{
    if (0 == iError) {
        NSLog(@"授权成功");
    }
    else {
        NSLog(@"onGetPermissionState %d",iError);
    }
}

//
@end
